import {ComponentWithStore} from 'mobx-miniprogram-bindings'
import {userStore} from '@/store/userstore'
import {reqCartList,reqUpdateChecked,reqCheckAllCart,reqAddCart,reqDelCart} from '@/api/cart'
// 导入miniprogram-computed提供的behavior
const computedBehavior = require('miniprogram-computed').behavior
// 导入debounce防抖方法
const {debounce} = require('miniprogram-licia');
import {swiperCellBehavior} from '@/behaviors/swiperCell'
ComponentWithStore({
  // 注册behavior
  behaviors:[computedBehavior,swiperCellBehavior],
  // 组件的属性列表
  storeBindings: {
    store:userStore,
    fields:['token']
  },
  computed:{
    // 判断是否全选，按钮全选按钮的选中效果
    // 计算属性会被挂载到data对象中
    selectAllStatus(data){
      // computed函数不能使用this来访问data中的数据
      // 如果想访问data中的数据，需要使用形参
      return (
        data.cartList.length !==0 && data.cartList.every(item=>item.isChecked===1)
      )
    },
    // 计算订单总金额
    totalPrice(data){
      let totalprice = 0
      data.cartList.forEach(item=>{
        if(item.isChecked===1){
          totalprice +=item.price*item.count
        }
      })
      return totalprice
    }
  },

  // 组件的初始数据
  data: {
    cartList: [],
    emptyDes: ''
  },

  // 组件的方法列表
  methods: {
    toOrder(){
      if(this.data.totalPrice===0){
        wx.toast({
          title:'请选择商品'
        })
        return
      }
      wx.navigateTo({
        url: '/module/orderPayModule/pages/order/detail/detail',
      })
    },
    // 删除购物车中的数量
     delCartGoods(e){
      const {id} = e.currentTarget.dataset
      wx.showModal({
        title: '删除',
        content: '您确定要删除吗',
        success:async(res)=>{
          if(res.confirm){
            await  reqDelCart(id)
           wx.toast({title:'删除成功'})
           this.showTipGetList()
          }
        }
      })
    },

    changeBuyNum:debounce( async function (e){
      const newBuyNum = e.detail >200 ? 200 : e.detail
      const {id,index,oldbuynum} = e.target.dataset
      const reg = /^([1-9]|[1-9]\d|1\d{2}|200)$/
      const regRes = reg.test(newBuyNum)
  
      if(!regRes){
        this.setData({
          [`cartList[${index}].count`]:oldbuynum
        })
        return
      }
      const disCount = newBuyNum - oldbuynum
      if(disCount ===0) return
    const res = await reqAddCart({goodsId:id,count:disCount})
    if(res.code===200){
      this.setData({
        [`cartList[${index}].count`]:newBuyNum,
        [`cartList[${index}].isChecked`]:1
      })
    }
    },500),
  async  updateChecked(e){
      const {detail} = e
      const {id,index} = e.target.dataset
      const isChecked = detail ? 1 : 0
      const res = await reqUpdateChecked(id,isChecked)
      if(res.code===200){
        this.showTipGetList()
      }
    },
    // 实现全选和全不选效果
   async selectAllStatus(e){
      // console.log(e);
      const {detail} = e
      const isChecked = detail ? 1 : 0
      const res = await reqCheckAllCart(isChecked)
      if(res.code===200){
        this.showTipGetList()
      }
    },
    // 展示文案同时获取购物车列表数据
  async  showTipGetList(){
      const {token} = this.data
      if(!token){
        this.setData({
          emptyDes:'您还没有登录',
          cartList:[] 
        })
        return // 不向下执行逻辑
      }
      const {code,data:cartList} = await reqCartList()
      if(code===200){
        this.setData({
          cartList,
          emptyDes:cartList.length ===0 && '还没添加商品'
        })
      }
    },
    onShow(){
      this.showTipGetList()
    },
    onHide(){
      this.onSwiperCellCommonClick()
    }
  }
})
